System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

47% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Facebook “People You May Know”
Image

Here is the system design for Facebook's "People You May Know" (PYMK) feature.

1. Problem Definition and Scope

We are designing the backend for the "People You May Know" recommendation engine. The goal is to suggest relevant connections to users to increase the density of the social graph and improve user engagement.

  • User Groups: Facebook users viewing their Feed or Friends tab.

  • Main Actions: Viewing the list, clicking "Add Friend," and clicking "Remove/Ignore."

  • Scope:

    • We will focus on the Friend-of-Friend (FoF) algorithm as the primary signal.

    • We will design the Data Pipeline (offline generation) and the API (online serving).

    • Out of Scope: We will not cover the frontend UI, deep learning models for image recognition, or the full "Friend Request" notification system.

Image

2. Clarify functional requirements

Must Have:

  • View Recommendations: Users can see a list of potential friends ranked by relevance.

  • Context: The system must show why a person is suggested (e.g., "15 Mutual Friends").

  • Add Friend: Users can send a friend request directly from the list.

  • Dismiss: Users can remove a suggestion so it does not appear again.

  • Already Connected Filter: The system must never suggest someone the user is already friends with.

Nice to Have:

  • Recent Updates: If I become friends with "Alice" now, the system should update my recommendations reasonably fast to show her friends.

  • Imported Contacts: Suggestions based on phone book matching.

Image

3. Clarify non functional requirements

  • Target Users: 2 Billion Daily Active Users (DAU).

  • Read vs Write:

    • Serving: Extremely Read Heavy (viewing the list).

    • Computation: Write Heavy (processing billions of edges in the background).

  • Latency:

    • Reading: < 200ms (must feel instant).

    • Freshness: Eventual consistency is acceptable. Recommendations can be generated daily via batch jobs.

  • Availability: 99.9%. It is better to show slightly stale suggestions than an error page.

  • Data Retention: The social graph is permanent. The generated suggestion lists are transient and regenerated frequently.

Image

4. Back of the envelope estimates

  • Traffic (Reads):
    • 2 Billion DAU.

    • Assume 50% of users view the PYMK widget daily.

    • .

    • Peak traffic (2x) .

  • Storage (Generated Lists):
    • We cannot compute "Friends of Friends" in real-time ( complexity). We must pre-compute them.

    • We store the top 100 suggestions for every active user.

    • Size per suggestion: 8 bytes (UserID) + 4 bytes (Score) = 12 bytes.

    • Size per user: .

    • Total Storage: .

    • This fits easily into a distributed Key-Value store or a large Redis cluster.

Image

5. API design

We will use a REST API.

1. Get Recommendations

  • Method: GET /v1/users/{user_id}/pymk
  • Parameters: limit (default 20), cursor (pagination).
  • Response:
{ "items": \[ { "user\_id": "98765", "mutual\_count": 15, "reason": "MUTUAL\_FRIENDS" } \], "next\_cursor": "abc-123" }
  • Note: The client fetches names and avatars separately using the User Profile Service to keep this response small.

2. Dismiss Suggestion

  • Method: DELETE /v1/users/{user_id}/pymk/{target_id}
  • Response: 200 OK
  • Description: Removes the user from the current cache and logs a negative signal.

3. Add Friend (Trigger)

  • Method: POST /v1/friendships
  • Body: { "to_id": "98765" }
  • Response: 201 Created

6. High level architecture

We will use a Hybrid Architecture: heavy offline batch processing to do the "hard math" and a fast online layer to serve the results.

  • API Service: Handles requests, fetches IDs from the Cache, and hydrates them with names/photos from the User Profile Service.

  • Recommendation Cache (Redis): Stores the pre-computed top 100 suggestions for every user for fast access.

  • Social Graph DB: The source of truth for all friendships (Edges).

  • Offline Batch Workers: A distributed cluster (Spark) that runs nightly to traverse the massive graph and calculate mutual friends.

Image

7. Data model

We need two primary data stores: one for the raw graph and one for the derived recommendations.

1. Social Graph (Source of Truth)

We need a database optimized for adjacency lists (finding all friends of a user).

  • Store: Graph DB (like Facebook's TAO) or Wide-Column Store (Cassandra).

  • Table: Edges

    • from_user_id (Partition Key)
    • to_user_id (Clustering Key)
    • status (active, pending, blocked)
    • created_at

2. Recommendation Store (Serving)

We need a Key-Value store for fast lookups by User ID.

  • Store: Redis (Sorted Sets) or Cassandra.

  • Key: pymk:{user_id}

  • Value: Sorted Set (ZSET) of Candidate IDs, scored by relevance.

    • Why ZSET? It allows us to keep the list sorted by "Mutual Friend Count" and efficiently remove items in if a user clicks "Ignore" or "Add".

8. Core flows end to end

We will divide the system into two distinct worlds: the Offline World (where we do the heavy math to find friends) and the Online World (where we instantly show those friends to the user).

Flow A: The "Heavy Lifting" (Offline Batch Generation)

Since checking billions of connections in real-time is too slow, we run a "Batch Job" (a massive background process) once every 24 hours. This job essentially "pre-bakes" the recommendations so they are ready when the user wakes up.

The Logic: "Triangle Closing"

The core idea is simple: If You know Alice, and Alice knows Bob, then You and Bob form an open triangle.

If we "close" that triangle, we introduce You to Bob. The more "Alices" (mutual friends) there are connecting you and Bob, the stronger the recommendation.

Step-by-Step Pipeline:

  1. Snapshot: The system takes a snapshot of the entire Social Graph (the huge database of who knows whom).

  2. Map Step (The Explosion):

    • The system looks at every user (let's call him the "Connector").
    • If the "Connector" is friends with both User A and User B, the system emits a "vote" that User A and User B should know each other.
    • Example: If you and I have 50 mutual friends, the system emits 50 separate "votes" linking us.
  3. Reduce Step (The Counting):

    • The system gathers all these "votes" and counts them.
    • It sees that User A and User B were linked 15 times.
    • Score = 15 (This is the "Mutual Friends" count).
  4. Filtering (The Cleanup):

    • Existing Friends: We check the graph: "Are User A and User B already friends?" If yes, discard the recommendation immediately.
    • Blocks: "Has User A blocked User B?" If yes, discard.
  5. Ranking & Storage:

    • We sort the remaining candidates by their Score (highest mutual friends first).
    • We pick the Top 100 candidates for User A.
    • We bulk-load these 100 IDs into the Recommendation Cache (Redis).
Image

Flow B: The "Fast Serving" (Online Read Path)

This is what happens when a user actually opens the Facebook app. This path must be lightning fast (under 200ms).

  1. Client Request:
    • The mobile app sends a request: GET /pymk.
  2. Cache Lookup:
    • The API Service goes directly to the Redis Cache (populated by the batch job above).

    • It fetches the list of 100 candidate IDs (e.g., [UserB, UserC, UserD...]).

  3. The "Last Mile" Filter (Crucial Step):
    • Problem: The batch job ran last night. What if the user added UserB as a friend this morning? We don't want to recommend them again.

    • Solution: The API checks a small, real-time "Recent Connections" cache or the main DB to filter out anyone the user befriended in the last 24 hours.

  4. Hydration:
    • Right now, the API only has IDs (e.g., "98765"). It needs names and photos.

    • It calls the User Profile Service with the list of IDs to get avatars, names, and mutual friend counts.

  5. Response:
    • The fully detailed JSON list is sent back to the phone.
Image

Flow C: Handling User Actions (Add or Ignore)

What happens when the user interacts with the list?

We need to update the view instantly without waiting for tomorrow's batch job.

  1. User Clicks "Ignore":
    • The client sends a DELETE request.

    • The API immediately removes that ID from the user's Redis Cache.

    • The user is also added to a "Blacklist" for the next batch job so they aren't recommended again tomorrow.

  2. User Clicks "Add Friend":
    • The client sends a POST request.

    • The API writes the new friendship to the Social Graph DB.

    • The API also removes that ID from the current Redis Cache (so the card disappears from the UI instantly).

Image

9. Caching and read performance

  • Strategy: Look-aside with heavy pre-computation.

  • Structure: Redis Sorted Set (ZSET).

    • Score: The number of mutual friends.
    • Member: The target_user_id.
  • Write-Through on Action:

    • On Ignore: If User A ignores User B, we call ZREM pymk:UserA UserB. This immediately removes them from the cached list so they don't reappear on refresh.

    • On Add: If User A adds User B, we also remove User B from the list immediately.

10. Storage, indexing and media

  • Primary Graph Storage:
    • Sharded by user_id. This ensures that "Get all friends for User X" is a single-server query.
  • Recommendation Storage:
    • We use a persistent store (like Cassandra) as a backup for the Redis cache. If Redis restarts, we reload from Cassandra.
  • Media Storage:
    • Profile pictures are stored in Object Storage (S3).
    • Served via CDN (Cloudflare/Akamai). The API returns the image URL; the browser fetches the actual pixels.

11. Scaling strategies

  • Sharding:
    • The Graph DB and Cache are both sharded by User ID.
    • We use Consistent Hashing to distribute data evenly.
  • Handling "Supernodes" (Celebrities):
    • A user with 5,000 friends creates pairs in the MapReduce job. This causes "data skew" and crashes workers.
    • Solution: We use Sampling. For supernodes, we only use their 500 most recent/active friends to generate suggestions. This caps the complexity.
  • Geographic Partitioning:
    • Friends are often local. We can run batch jobs for "North America Users" separately from "Asia Users" to localize data transfer.

12. Reliability, failure handling and backpressure

  • Stale Data Fallback:
    • If the Spark job fails tonight, we simply serve yesterday's data from the cache. Old suggestions are better than no suggestions.
  • Empty States (Cold Start):
    • New users have 0 friends, so the "Friends of Friends" algorithm returns nothing.

    • Fallback: We show "Popular Users in your City" or "Alumni from your University" until they make their first few connections.

  • Circuit Breakers:
    • If the User Profile Service is overloaded, the PYMK API degrades gracefully (e.g., returning fewer results or hiding the widget) to prevent cascading failures.

13. Security, privacy and abuse

  • Privacy (Critical):
    • Block Lists: If User A blocks User B, our algorithm must filter B out. This check happens in the Batch Filter step AND the Real-Time Filter step.
    • Visibility Settings: We respect "Who can look me up?" settings.
  • Abuse Prevention:
    • Rate Limiting: Users cannot refresh the list 100 times/second to scrape user data.
    • Fake Accounts: We filter out accounts flagged as "Potential Spam" from being recommended.

14. Bottlenecks and next steps

  • Bottleneck: Graph Traversal Complexity. As the graph grows, the batch job becomes too expensive.
    • Next Step: Switch from brute-force "Triangle Closing" to Random Walk algorithms (like Personalized PageRank). These algorithms "wander" the graph to find close connections without checking every single path, which is much faster.
  • Bottleneck: Data Staleness. Batch recommendations are 24 hours old.
    • Next Step: Implement Streaming Updates. Use a Kafka stream to listen for "New Friendship" events and trigger a mini-update for the involved users' caches immediately.

Summary

  1. Architecture: Hybrid approach with Offline Batch (Spark) for generation and Online Cache (Redis) for serving.

  2. Algorithm: Uses Friends-of-Friends (Triangle Count) executed via MapReduce.

  3. Scale: Handles 2B users by sharding by User ID and sampling supernodes.

  4. Resilience: Prioritizes availability; serves stale data if the pipeline fails.

Design Stock Exchange
Design LinkedIn Connections
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow A: The "Heavy Lifting" (Offline Batch Generation)

Flow B: The "Fast Serving" (Online Read Path)

Flow C: Handling User Actions (Add or Ignore)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary